package commands

import (
	"context"
	"fmt"
	"os"
	"syscall"

	"github.com/containerd/containerd"
	"github.com/containerd/containerd/namespaces"
	cli "github.com/urfave/cli/v3"
)

var stopCommand = &cli.Command{
	Name:      "stop",
	Usage:     "Stop one or more containers.",
	UsageText: "ruc stop [options] CONTAINER [CONTAINER...]",

	Action: stop,

	ErrWriter:       os.Stderr,
	CommandNotFound: commandNotFoundHandler,
	ExitErrHandler:  exitErrHandler,
}

func stop(ctx context.Context, cmd *cli.Command) error {
	if cmd.NArg() < 1 {
		return ErrNoContainerProvided
	}

	client, err := containerd.New(
		containerdAddress,
		containerd.WithDefaultNamespace(namespaces.Default),
	)
	if err != nil {
		return err
	}
	defer client.Close()

	for _, containerID := range cmd.Args().Slice() {
		container, err := client.LoadContainer(ctx, containerID)
		if err != nil {
			fmt.Fprintf(cmd.ErrWriter, "%q: %s\n", cmd.FullName(), err)
			continue
		}

		task, err := container.Task(ctx, nil)
		if err != nil {
			fmt.Fprintf(cmd.ErrWriter, "%q: %s\n", cmd.FullName(), err)
			continue
		}

		// 发送 SIGTERM
		err = task.Kill(ctx, syscall.Signal(15))
		if err != nil {
			fmt.Fprintf(cmd.ErrWriter, "%q: %s\n", cmd.FullName(), err)
			continue
		}
	}

	return nil
}
